package mce.cuce;

import java.util.ArrayList;

import org.apache.commons.validator.UrlValidator;

public class UrlUtilities {
	private static String alphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
	
	/**
	 * Checks whether the url is valid one.
	 * @return true if valid false otherwise.
	 */
	public static boolean isValid(String url) {
		/*to use UrlValidator class:
		 *  commons-validator-1.3.1.jar and oro-2.0.7.jar files
			must be in the project.
		*/
		UrlValidator validator = new UrlValidator();
		return validator.isValid(url);
	}
	
	/**
	 * Shortens the long url. Must return a unique value for each longUrl.
	 * @param longUrl
	 * @return the short url.
	 */
	public static String shortenUrl(String longUrl) {
		int id = DbService.getNextId();
		String shortUrl = base62_encode(id);
		
		return shortUrl;
	}
	
	/**
	 * Converts the given number into a new base number.
	 * @param number to be converted.
	 * @return
	 */
	public static String base62_encode(int number) {
		
		ArrayList<String> result = new ArrayList<String>();
		
		int base = alphabet.length();
		
		if(number <= 0 ) {
			return alphabet.substring(0, 1);
		} else if(number <= base) {
			return alphabet.substring(number, number+1);
		}
		
		while(number > base) {
			int rem = number % base;
			result.add((alphabet.substring(rem, rem + 1)));
			number = number / base;			
		}
		
		result.add((alphabet.substring(number, number + 1)));
		
		String resultStr ="";
		for(int i = result.size() -1; i >= 0; i--) {
			resultStr = resultStr.concat(result.get(i));
		}
		
		return resultStr;
	}
	
	/**
	 * Given number returns an int in base 10, which corresponds to numbers database id.
	 * @param number base 62 number, part after the last slash in short urls.
	 * @return
	 */
	public static int base62_decode(String number) {
		
		int base = alphabet.length();
		int strlen = number.length();
		int num = 0;
				
		for(int i=0; i<strlen; i++) {
			int power = (strlen - (i + 1));
			num +=(int) (alphabet.indexOf(number.charAt(i)) * (Math.pow(base, power)));
		}
		
		return num;
	}
}
